import BButton from "../btoolkit/components/BButton";
import SDKManager, { Platform } from "../btoolkit/sdk/SDKManager";
import QuLe, { EventOnRemoteConfigLoaded } from "../btoolkit/sdk/QuLe";
import EventManager from "../btoolkit/EventManager";
import TouTiaoUtils from "../btoolkit/sdk/toutiao/TouTiaoUtils";
import App from "../btoolkit/framework/App";

const { ccclass, property } = cc._decorator;

@ccclass
export default class FriendlyLinkBar extends cc.Component {

    @property(cc.SpriteAtlas)
    atlas: cc.SpriteAtlas = null;

    @property(cc.Node)
    item: cc.Node = null;

    static instance: FriendlyLinkBar = null;
    speed = 30;
    space = 115;
    itemsLength = 0;
    firstItem: cc.Node;
    previousY = 0;
    delta = 0;
    canMove = false;
    private isAlignLeft = false;

    onLoad() {
        FriendlyLinkBar.instance = this;
        if (QuLe.instance.remoteConfig) {
            this.createUI();
        } else {
            EventManager.addEvent(EventOnRemoteConfigLoaded, () => {
                this.createUI();
            });
        }
        this.node.active = false;
    }

    start(){
        this.isAlignLeft = this.node.getComponent(cc.Widget).isAlignLeft;
        if (this.isAlignLeft) {
            this.setToLeft();
        } else {
            this.setToRight();
        }
    }

    setToLeft() {
        let widget: cc.Widget = this.node.getComponent(cc.Widget);
        widget.isAlignLeft = true;
        widget.isAlignRight = false;
        widget.left = App.instance.isLiuHaiScreen ? 72 : 12;
    }

    setToRight() {
        let widget: cc.Widget = this.node.getComponent(cc.Widget);
        widget.isAlignLeft = false;
        widget.isAlignRight = true;
        widget.right = App.instance.isLiuHaiScreen ? 72 : 12;
    }

    private createUI() {
        if (SDKManager.platform == Platform.WeiXin) {
            if (!QuLe.instance.remoteConfig.friendLink) {
                console.log('互跳功能已关闭');
                return;
            }
            this.node.active = true;
            this.item.active = true;
            this.createScrollItems();
        } else if (SDKManager.platform == Platform.TouTiao) {
            if (!QuLe.instance.remoteConfig.friendLinkDialog) {
                console.log('互跳功能已关闭');
                return;
            }
            if (!TouTiaoUtils.isIOS) {
                this.node.active = true;
                this.item.getComponent(cc.Sprite).spriteFrame = this.atlas.getSpriteFrame('gengduoyouxi1');
                this.item.getChildByName('icon').destroy();
                this.item.width = this.item.height = 140;
                BButton.addButton(this.item).setTouchUpEvent(() => { SDKManager.instance.showOtherGamesDialog() });
            }
        } else {
            if (!QuLe.instance.remoteConfig.friendLink) {
                console.log('互跳功能已关闭');
                return;
            }
            this.node.active = true;
            this.item.active = true;
            this.createScrollItems();
        }
    }

    private createScrollItems() {
        let ShowGames = this.getShowGames();
        //开始动态创建icon
        for (let i = 0; i < ShowGames.length; i++) {
            let itemNode: cc.Node = null;
            if (i == 0) {
                itemNode = this.item;
            } else {
                itemNode = cc.instantiate(this.item);
                itemNode.parent = this.item.parent;
            }
            itemNode.active = true;
            let data = ShowGames[i];
            itemNode.getChildByName('icon').getComponent(cc.Sprite).spriteFrame = this.atlas.getSpriteFrame(data.frame);
            itemNode.y = -itemNode.height * 0.5 - this.space * i;
            BButton.addButton(itemNode).setTouchUpEvent(() => { SDKManager.instance.navigateToOtherGame(data) });
        }

        //开始创建控制
        this.node.on(cc.Node.EventType.TOUCH_START, this.onTouchDown, this);
        this.node.on(cc.Node.EventType.TOUCH_MOVE, this.onTouchMove, this);
        this.node.on(cc.Node.EventType.TOUCH_END, this.onTouchUp, this);
        this.node.on(cc.Node.EventType.TOUCH_CANCEL, this.onTouchUp, this);

        this.itemsLength = this.node.children.length;
        this.firstItem = this.node.children[0];

        this.scheduleOnce(() => {
            this.canMove = this.space * (this.itemsLength - 1) + this.firstItem.height > this.node.height;
        }, 0.5);
    }

    update(dt: number) {
        if (!this.canMove) {
            return;
        }
        let speed = this.speed * dt + this.delta;
        let length = this.itemsLength;
        if (speed > 0) {
            let firstItem = this.firstItem;
            if (firstItem) {
                let items = this.node.children;
                firstItem.y += speed;
                if (firstItem.y > firstItem.height * 0.5) {
                    firstItem.setSiblingIndex(length - 1);
                    firstItem = this.firstItem = items[0];
                }
                for (let i = 0; i < length; i++) {
                    let item = items[i];
                    if (item != firstItem) {
                        item.y = firstItem.y - this.space * i;
                    }
                }
            }
        } else {
            let lastItem = this.node.children[length - 1];
            if (lastItem) {
                let items = this.node.children;
                lastItem.y += speed;
                if (lastItem.y < -this.node.height - lastItem.height * 0.5) {
                    lastItem.setSiblingIndex(0);
                    lastItem = items[length - 1];
                }
                for (let i = 0; i < length; i++) {
                    let item = items[i];
                    if (item != lastItem) {
                        item.y = lastItem.y + this.space * (length - i - 1);
                    }
                }
            }
        }
    }

    onTouchDown(e: cc.Event.EventTouch) {
        this.previousY = e.getLocation().y;
    }

    onTouchMove(e: cc.Event.EventTouch) {
        let ePosY = e.getLocation().y;
        this.delta = ePosY - this.previousY;
        this.previousY = ePosY;
    }

    onTouchUp(e: cc.Event.EventTouch) {
        this.delta = 0;
        this.firstItem = this.node.children[0];
    }

    /** 选出远程配置里存在的游戏 */
    getShowGames() {
        if (!QuLe.instance.remoteConfig) {
            console.error('远程配置文件未准备好');
            return;
        }
        let AllGames = SDKManager.instance.getAllGamesConfig();
        let showGames = [];
        let allGamesCount = AllGames.length;
        let appIds = QuLe.instance.remoteConfig.appIds;
        let appIdsCount = appIds.length;
        for (let i = 0; i < allGamesCount; i++) {
            let game = AllGames[i];
            let isContains = false;
            for (let j = 0; j < appIdsCount; j++) {
                let wxAppId = appIds[j];
                if (game.appId == wxAppId) {
                    isContains = true;
                    break;
                }
            }
            if (isContains) {
                showGames.push(game);
            }
        }
        return showGames;
    }

}
